<template>
	<view class="container">
		
		<!-- 视图切换按钮 -->
		<view class="view-switch">
			<view 
				class="switch-btn" 
				:class="{active: viewMode === 'calendar'}"
				@click="switchView('calendar')"
			>
				日历视图
			</view>
			<view 
				class="switch-btn" 
				:class="{active: viewMode === 'list'}"
				@click="switchView('list')"
			>
				列表视图
			</view>
		</view>
		
		<!-- 日历视图 -->
		<view class="calendar-section" v-if="viewMode === 'calendar'">
			<view class="calendar-header">
				<view class="calendar-nav">
					<view class="nav-btn" @click="prevMonth">‹</view>
					<text class="current-month">{{currentYear}}年{{currentMonth + 1}}月</text>
					<view class="nav-btn" @click="nextMonth">›</view>
				</view>
			</view>
			
			<view class="calendar-weekdays">
				<view class="weekday" v-for="day in weekDays" :key="day">{{day}}</view>
			</view>
			
			<view class="calendar-days">
				<view 
					class="calendar-day" 
					v-for="day in calendarDays" 
					:key="day.date"
					:class="{
						'other-month': !day.isCurrentMonth,
						'today': isToday(day.date),
						'selected': isSelected(day.date),
						'has-reminder': hasReminderOnDate(day.date)
					}"
					@click="selectDate(day)"
				>
					<text class="day-number">{{day.day}}</text>
					<view v-if="hasReminderOnDate(day.date)" class="reminder-dot"></view>
				</view>
			</view>
			
			<!-- 选中日期的健康提醒 -->
			<view v-if="selectedDate" class="selected-date-reminders">
				<view class="section-title">
					{{ formatSelectedDate() }} 的健康提醒
				</view>
				<view v-if="selectedDateReminders.length > 0" class="reminders-list">
					<view 
						v-for="reminder in selectedDateReminders" 
						:key="reminder.id"
						class="reminder-item"
						@click="viewHealthDetail(reminder.id)"
					>
						<view class="reminder-icon">{{ getHealthIcon(reminder.type) }}</view>
						<view class="reminder-info">
							<view class="reminder-header">
								<view class="reminder-title">{{ reminder.content }}</view>
								<view class="reminder-pet">{{ getPetName(reminder.petId) }}</view>
							</view>
							<view class="reminder-time">{{ formatDateTime(reminder.recordDate) }}</view>
						</view>
						<view class="reminder-status" :class="getStatusClass(reminder.status)">
							{{ getStatusText(reminder.status) }}
						</view>
					</view>
				</view>
				<view v-else class="empty-state">
					<text class="empty-text">暂无健康提醒</text>
				</view>
			</view>
		</view>
		
		<!-- 列表视图 -->
		<view class="list-view" v-if="viewMode === 'list'">
			<view class="section-title">
				健康记录列表
			</view>
			<view class="reminder-list">
				<view 
					class="list-item" 
					v-for="record in healthRecords" 
					:key="record.id"
					@click="viewHealthDetail(record.id)"
				>
					<view class="list-item-header">
						<view class="list-item-title">{{record.content}}</view>
						<view class="list-item-pet">{{getPetName(record.petId)}}</view>
					</view>
					<view class="list-item-info">
						<text class="list-item-time">{{formatDateTime(record.recordDate)}}</text>
						<text class="list-item-status" :class="getStatusClass(record.status)">{{ getStatusText(record.status) }}</text>
					</view>
				</view>
			</view>
			
			<!-- 列表视图空状态 -->
			<view class="empty-state" v-if="!loading && healthRecords.length === 0">
				<text class="empty-text">暂无健康记录</text>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-state" v-if="loading">
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 悬浮添加按钮 -->
		<view class="fab" @click="addHealthRecord">
			<text class="fab-icon">+</text>
		</view>
	</view>
</template>

<script>
import { getUserId, checkAndRedirectToLogin } from '@/utils/auth.js'
import { getPetList } from '@/api/pet.js'
import { getHealthList, deleteHealthRecord } from '@/api/health.js'

export default {
	data() {
		return {
			loading: false,
			healthRecords: [],
			pets: [],
			currentFilter: 'all',
			petId: null,
			viewMode: 'calendar', // 'calendar' 或 'list'
			// 日历相关数据
			currentYear: new Date().getFullYear(),
			currentMonth: new Date().getMonth(),
			selectedDate: new Date(),
			calendarDays: [],
			weekDays: ['日', '一', '二', '三', '四', '五', '六']
		}
	},
	computed: {
		filteredRecords() {
			if (this.currentFilter === 'all') {
				return this.healthRecords
			}
			return this.healthRecords.filter(record => record.type === this.currentFilter)
		},
		totalRecords() {
			return this.healthRecords.length
		},
		reminderCount() {
			return this.healthRecords.filter(record => record.nextRemindTime).length
		},
		completedCount() {
			return this.healthRecords.filter(record => this.isCompletedStatus(record.status)).length
		},
		// 选中日期的提醒列表
		selectedDateReminders() {
			if (!this.selectedDate) return []
			const selectedDateStr = this.formatDate(this.selectedDate)
			return this.healthRecords.filter(record => {
				const recordDate = this.formatDate(new Date(record.recordDate))
				return recordDate === selectedDateStr
			})
		}
	},
	onLoad() {
		this.loadPets()
		// 监听健康记录更新事件
		uni.$on('healthrecordupdated', () => {
			
			this.loadHealthRecords()
		})
	},
	onShow() {
		this.loadHealthRecords()
	},
	watch: {
		healthRecords: {
			handler() {
				this.generateCalendar()
			},
			immediate: true
		},
		currentMonth() {
			this.generateCalendar()
		},
		currentYear() {
			this.generateCalendar()
		}
	},
	onUnload() {
		// 移除事件监听
		uni.$off('healthrecordupdated')
	},
	onReady() {
	},
	methods: {
		// 生成日历
		generateCalendar() {
			const year = this.currentYear
			const month = this.currentMonth
			
			// 获取当月第一天
			const firstDay = new Date(year, month, 1)
			// 获取当月最后一天
			const lastDay = new Date(year, month + 1, 0)
			// 获取第一天是周几（0为周日）
			const firstDayWeek = firstDay.getDay()
			// 获取最后一天是周几
			const lastDayWeek = lastDay.getDay()
			
			const days = []
			
			// 添加上个月的最后几天
			const prevMonthLastDay = new Date(year, month, 0).getDate()
			for (let i = firstDayWeek - 1; i >= 0; i--) {
				const day = prevMonthLastDay - i
				const date = new Date(year, month - 1, day)
				days.push({
					day,
					date: this.formatDate(date),
					isCurrentMonth: false,
					hasReminder: this.hasReminderOnDate(date)
				})
			}
			
			// 添加当月的所有天
			for (let i = 1; i <= lastDay.getDate(); i++) {
				const date = new Date(year, month, i)
				days.push({
					day: i,
					date: this.formatDate(date),
					isCurrentMonth: true,
					hasReminder: this.hasReminderOnDate(date)
				})
			}
			
			// 添加下个月的前几天
			for (let i = 1; i <= 6 - lastDayWeek; i++) {
				const date = new Date(year, month + 1, i)
				days.push({
					day: i,
					date: this.formatDate(date),
					isCurrentMonth: false,
					hasReminder: this.hasReminderOnDate(date)
				})
			}
			
			this.calendarDays = days
		},
		

		
		// 选择日期
		selectDate(day) {
			this.selectedDate = new Date(day.date)
		},
		
		// 判断是否为今天
		isToday(date) {
			const today = new Date()
			const dateObj = new Date(date)
			return dateObj.getDate() === today.getDate() &&
			       dateObj.getMonth() === today.getMonth() &&
			       dateObj.getFullYear() === today.getFullYear()
		},
		
		// 判断是否为选中的日期
		isSelected(date) {
			if (!this.selectedDate) return false
			const dateObj = new Date(date)
			const selectedObj = new Date(this.selectedDate)
			return dateObj.getDate() === selectedObj.getDate() &&
			       dateObj.getMonth() === selectedObj.getMonth() &&
			       dateObj.getFullYear() === selectedObj.getFullYear()
		},
		
		// 判断指定日期是否有提醒
		hasReminderOnDate(date) {
			const dateStr = this.formatDate(date)
			return this.healthRecords.some(record => {
				const recordDate = this.formatDate(new Date(record.recordDate))
				return recordDate === dateStr
			})
		},
		
		// 上一个月
		prevMonth() {
			if (this.currentMonth === 0) {
				this.currentMonth = 11
				this.currentYear--
			} else {
				this.currentMonth--
			}
		},
		
		// 下一个月
		nextMonth() {
			if (this.currentMonth === 11) {
				this.currentMonth = 0
				this.currentYear++
			} else {
				this.currentMonth++
			}
		},
		
		// 格式化日期为 YYYY-MM-DD
		formatDate(date) {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		
		// 格式化选中的日期
		formatSelectedDate() {
			if (!this.selectedDate) return ''
			const date = new Date(this.selectedDate)
			return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
		},
		
		// 切换视图
		switchView(mode) {
			this.viewMode = mode
		},
		
		// 获取宠物名称
		getPetName(petId) {
			if (!petId) return '未知宠物'
			// 处理数据类型不匹配问题：petId可能是字符串或数字
			const pet = this.pets.find(p => {
				// 将两个id都转换为字符串进行比较
				return String(p.id) === String(petId)
			})
			return pet ? pet.name : '未知宠物'
		},
		
		async loadPets() {
			try {
				// 使用统一的认证检查函数
				if (!checkAndRedirectToLogin('请先登录')) {
					return
				}
				
				const userId = getUserId()
				const response = await getPetList(userId)
				
				if (response && response.code === 200) {
					const petData = response.rows || response.data || []
					this.pets = petData
				}
			} catch (error) {
				
			}
		},
		
		async loadHealthRecords() {
			this.loading = true
			try {
				const response = await getHealthList({
					pageNum: 1,
					pageSize: 100
				})
				
				// 使用统一API后的响应格式
				if (response && response.code === 200) {
					const data = response.rows || response.data || []
					
					if (data && data.length > 0) {
						// 直接赋值
						this.healthRecords = data
						// 添加调试日志：检查每条记录的status字段
						data.forEach((record, index) => {
							console.log(`debug - record ${index} status:`, record.status, 'type:', typeof record.status, 'full record:', record)
						})
					} else {
						this.healthRecords = []
					}
				} else {
					this.healthRecords = []
				}
			} catch (error) {
				
				this.healthRecords = []
			} finally {
				this.loading = false
			}
		},
		
		filterRecords(filter) {
			this.currentFilter = filter
		},
		
		getHealthIcon(type) {
			const icons = {
				'疫苗': '💉',
				'驱虫': '🦠',
				'体检': '🏥',
				'体重': '⚖️'
			}
			return icons[type] || '📋'
		},
		isPendingStatus(status) {
			// 统一判断待处理状态：支持数字0、字符串'0'、英文'pending'
			return status === '0' || status === 0 || status === 'pending'
		},
		isCompletedStatus(status) {
			// 统一判断已完成状态：支持数字1、字符串'1'、英文'completed'
			return status === '1' || status === 1 || status === 'completed'
		},
		
		// 获取状态文本
		getStatusText(status) {
			// 添加调试日志
			console.log('debug - getStatusText called with status:', status, 'type:', typeof status)
			if (this.isPendingStatus(status)) {
				return '待处理'
			} else if (this.isCompletedStatus(status)) {
				return '已完成'
			} else {
				return '已逾期'
			}
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			// 添加调试日志
			console.log('debug - getStatusClass called with status:', status, 'type:', typeof status)
			if (this.isPendingStatus(status)) {
				return 'pending'
			} else if (this.isCompletedStatus(status)) {
				return 'completed'
			} else {
				return 'overdue'
			}
		},
		
		formatDateTime(dateTime) {
			const date = new Date(dateTime)
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
		},
		
		viewHealthDetail(recordId) {
			uni.navigateTo({
				url: `/pages/health/detail?id=${recordId}`
			})
		},
		
		editHealthRecord(recordId) {
			
			uni.navigateTo({
				url: `/pages/health/edit?id=${recordId}`,
				success: (res) => {
					
				},
				fail: (err) => {
					
					uni.showToast({
						title: '无法打开编辑页面',
						icon: 'none'
					});
				}
			});
		},
		
		addHealthRecord() {
			uni.navigateTo({
				url: '/pages/health/add'
			})
		},
		
		async deleteHealthRecord(recordId) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个健康记录吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await deleteHealthRecord(recordId)
							
							// 处理 uni.request 的响应格式
							let responseData = response
							
							// 如果响应是数组格式 [error, response]，取第二个元素
							if (Array.isArray(response) && response.length === 2) {
								const [error, data] = response
								if (error) {
									
									uni.showToast({
										title: '网络请求失败',
										icon: 'none'
									})
									return
								}
								responseData = data
							}
							
							// 检查响应状态
							if (responseData && responseData.code === 200) {
								const data = responseData.data
								
								// 删除成功通常返回 code: 200
								if (data && data.code === 200) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									})
									// 重新加载列表
									this.loadHealthRecords()
								} else {
									// 即使业务逻辑返回失败，如果HTTP状态是200，说明请求成功
									// 可能是后端删除成功但返回了其他状态码
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									})
									this.loadHealthRecords()
								}
							} else {
								// HTTP错误
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								})
							}
						} catch (error) {
							
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							})
						}
					}
				}
			})
		}
	} // End of methods
}
</script>

<style scoped>
.container {
	padding: 20rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 视图切换样式 */
.view-switch {
	display: flex;
	background: white;
	border-radius: 25rpx;
	padding: 8rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.switch-btn {
	flex: 1;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 20rpx;
	font-size: 26rpx;
	color: #666;
	transition: all 0.3s ease;
	cursor: pointer;
}

.switch-btn.active {
	background: #007AFF;
	color: white;
	font-weight: bold;
}

/* 列表视图样式 */
.list-view {
	background: white;
	border-radius: 15rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.list-item {
	padding: 30rpx 20rpx;
	margin-bottom: 15rpx;
	background: #f8f8f8;
	border-radius: 10rpx;
	cursor: pointer;
	transition: all 0.3s ease;
	border-left: 6rpx solid #007AFF;
}

.list-item:active {
	background: #e8e8e8;
	transform: scale(0.98);
}

.list-item-header {
	display: flex;
	align-items: center;
	margin-bottom: 15rpx;
	text-align: left;
}

.list-item-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	text-align: left;
	margin-right: 15rpx;
}

.list-item-pet {
	font-size: 24rpx;
	color: #007aff;
	background: rgba(0, 122, 255, 0.1);
	padding: 6rpx 16rpx;
	border-radius: 20rpx;
	white-space: nowrap;
	text-align: left;
}

.list-item-info {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	text-align: left;
}

.list-item-time {
	font-size: 26rpx;
	color: #666;
	text-align: left;
}



.stats-section {
	display: flex;
	justify-content: space-between;
	margin-bottom: 30rpx;
}

.stat-card {
	background: white;
	padding: 30rpx;
	border-radius: 15rpx;
	text-align: center;
	flex: 1;
	margin: 0 10rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.stat-number {
	font-size: 36rpx;
	font-weight: bold;
	color: #007AFF;
	display: block;
}

.stat-label {
	font-size: 24rpx;
	color: #666;
	margin-top: 10rpx;
}

/* 日历样式 */
.calendar-section {
	background: white;
	border-radius: 15rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.calendar-header {
	margin-bottom: 20rpx;
}

.calendar-nav {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 20rpx;
}

.nav-btn {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	background: #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	color: #666;
	cursor: pointer;
}

.current-month {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.calendar-weekdays {
	display: flex;
	margin-bottom: 10rpx;
}

.weekday {
	flex: 1;
	text-align: center;
	font-size: 24rpx;
	color: #666;
	padding: 10rpx 0;
}

.calendar-days {
	display: flex;
	flex-wrap: wrap;
}

.calendar-day {
	width: 14.28%;
	height: 80rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;
	cursor: pointer;
	border-radius: 8rpx;
	margin: 5rpx 0;
}

.day-number {
	font-size: 28rpx;
	color: #333;
}

.calendar-day.other-month .day-number {
	color: #ccc;
}

.calendar-day.today .day-number {
	color: #007AFF;
	font-weight: bold;
}

.calendar-day.selected {
	background: #007AFF;
}

.calendar-day.selected .day-number {
	color: white;
}

/* 提醒点样式 */
.calendar-day.has-reminder .reminder-dot {
	width: 8rpx;
	height: 8rpx;
	background: #ff4757;
	border-radius: 50%;
	position: absolute;
	bottom: 8rpx;
	left: 50%;
	transform: translateX(-50%);
}

/* 选中日期的提醒列表样式 */
.selected-date-reminders {
	margin-top: 30rpx;
	padding: 20rpx;
	background: white;
	border-radius: 15rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.reminders-list {
	margin-bottom: 20rpx;
}

.reminder-item {
	display: flex;
	align-items: center;
	padding: 20rpx;
	margin-bottom: 15rpx;
	background: #f8f8f8;
	border-radius: 10rpx;
	cursor: pointer;
	transition: all 0.3s ease;
}

.reminder-item:active {
	background: #e8e8e8;
	transform: scale(0.98);
}

.reminder-icon {
	margin-right: 20rpx;
	font-size: 32rpx;
}

.reminder-info {
	flex: 1;
}

.reminder-header {
	display: flex;
	align-items: center;
	margin-bottom: 8rpx;
	text-align: left;
}

.reminder-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-right: 15rpx;
}

.reminder-time {
	font-size: 24rpx;
	color: #666;
	text-align: left;
}

.reminder-status {
	font-size: 22rpx;
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
}

.reminder-status.pending {
	background: #FFF3CD;
	color: #856404;
}

.reminder-status.completed {
	background: #d4edda;
	color: #155724;
}

.reminder-status.overdue {
	background: #f8d7da;
	color: #721c24;
}



/* 提醒列表样式 */
.reminder-section {
	background: white;
	border-radius: 15rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.section-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	padding-bottom: 15rpx;
	border-bottom: 1rpx solid #eee;
}

.reminder-list {
	margin-bottom: 120rpx;
}

.reminder-item {
	display: flex;
	align-items: center;
	padding: 20rpx;
	margin-bottom: 15rpx;
	background: #f8f8f8;
	border-radius: 10rpx;
	cursor: pointer;
	transition: all 0.3s ease;
}

.reminder-item:active {
	background: #e8e8e8;
	transform: scale(0.98);
}

.reminder-icon {
	margin-right: 20rpx;
}

.reminder-info {
	flex: 1;
}

.reminder-header {
	display: flex;
	align-items: center;
	margin-bottom: 8rpx;
	text-align: left;
}

.reminder-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-right: 15rpx;
}



.reminder-type {
	font-size: 24rpx;
	color: #007AFF;
	margin-right: 15rpx;
}

.reminder-pet {
	font-size: 24rpx;
	color: #007aff;
	background: rgba(0, 122, 255, 0.1);
	padding: 4rpx 12rpx;
	border-radius: 16rpx;
	white-space: nowrap;
}

.reminder-status {
	font-size: 22rpx;
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
}

.reminder-status.pending {
	background: #FFF3CD;
	color: #856404;
}

.reminder-status.completed {
	background: #d4edda;
	color: #155724;
}

.reminder-status.overdue {
	background: #f8d7da;
	color: #721c24;
}

.list-item-status {
	font-size: 22rpx;
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
	margin-left: 10rpx;
}

.list-item-status.pending {
	background: #fff3cd;
	color: #856404;
}

.list-item-status.completed {
	background: #d4edda;
	color: #155724;
}

.list-item-status.overdue {
	background: #f8d7da;
	color: #721c24;
}

.loading-state {
	text-align: center;
	padding: 100rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}

.empty-state {
	text-align: center;
	padding: 100rpx 0;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
	display: block;
	margin-bottom: 30rpx;
}

.fab {
	position: fixed;
	bottom: 140rpx; /* 调整位置，避免被底部导航栏遮挡 */
	right: 40rpx;
	width: 100rpx;
	height: 100rpx;
	background: #007AFF;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 20rpx rgba(0,122,255,0.3);
	z-index: 999; /* 确保在最上层 */
}

.fab-icon {
	color: white;
	font-size: 40rpx;
	font-weight: bold;
}
</style>